package com.auxgroup.smarthome.openapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.openapi.requestbody.*;
import com.auxgroup.smarthome.openapi.responsebody.*;
import com.auxgroup.smarthome.util.WebClientUtils;
import com.auxgroup.smarthome.util.WebUtils;
import com.auxgroup.smarthome.utils.EncryptionUtils;
import com.auxgroup.smarthome.utils.HttpClientUtil;
import com.auxgroup.smarthome.utils.MapJsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by kevinchen on 2017/3/8.
 */
public class OpenApi {
    private static final Logger logger = LoggerFactory.getLogger(OpenApi.class);
    /**
     * 匿名登录
     *
     * @param appId
     * @param phone_id
     * @return
     */
    public static UserTokenMsg anonymousLogin(String appId, String phone_id) {
        String result = HttpClientUtil.httpRequest(OpenUrl.anonymousLogin.getUri(), OpenUrl.anonymousLogin.getHeaderMap(appId), MapJsonUtils.put(new String[]{"phone_id", phone_id}), OpenUrl.anonymousLogin.getMethodType());
        return JSON.parseObject(result, UserTokenMsg.class);
    }

    /**
     * 根据 MAC 绑定设备
     *
     * @param appId
     * @param token
     * @param product_secret
     * @param bindMacDeviceInfo
     * @return
     */
    public static BindedDeviceInfo bindMac(String appId, String token, String product_secret, BindMacDeviceInfo bindMacDeviceInfo) {
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String signature = EncryptionUtils.md5(product_secret + timestamp).toLowerCase();
        String result = HttpClientUtil.httpRequest(OpenUrl.bindMac.getUri(), OpenUrl.bindMac.getHeaderMap(appId, token, timestamp, signature), JSON.toJSONString(bindMacDeviceInfo), OpenUrl.bindMac.getMethodType());
        return JSON.parseObject(result, BindedDeviceInfo.class);
    }

    /**
     * 获取用户绑定设备列表
     *
     * @param appId
     * @param token
     * @param params
     * @return
     */
    public static BindedDeviceList bindedDeviceList(String appId, String token, int... params) {
        Map<String, String> paramMap = null;
        String[] paramNames = new String[]{"limit", "skip", "show_disabled", "show_proto_ver"};
        if (params == null || params.length == 0) {
            paramMap = MapJsonUtils.put(new String[]{"limit", String.valueOf(10)});
        } else {
            String[][] paramAry = new String[params.length][2];
            for (int i = 0; i < params.length; i++) {
                paramAry[i] = new String[]{paramNames[i], String.valueOf(params[i])};
            }
            paramMap = MapJsonUtils.put(paramAry);
        }
        String result = HttpClientUtil.httpRequest(OpenUrl.deviceList.getUri(), OpenUrl.deviceList.getHeaderMap(appId, token), paramMap, OpenUrl.deviceList.getMethodType());
        return JSON.parseObject(result, BindedDeviceList.class);
    }


    public static JSONObject getDevicedata(String appId, String did) {
        String result = HttpClientUtil.httpRequest(OpenUrl.devdata.getUri(did), OpenUrl.devdata.getHeaderMap(appId), "", OpenUrl.devdata.getMethodType());
        return JSON.parseObject(result);
    }

    /**
     * 手机号注册
     *
     * @param appId
     * @param phone
     * @param code
     * @return
     */
    public static UserTokenMsg registerPhone(String appId, String phone, String password, String code) {
        String result = HttpClientUtil.httpRequest(OpenUrl.CREATE_USER.getUri(), OpenUrl.CREATE_USER.getHeaderMap(appId), MapJsonUtils.put(new String[]{"phone", phone}, new String[]{"password", password}, new String[]{"code", code}), OpenUrl.anonymousLogin.getMethodType());
        return JSON.parseObject(result, UserTokenMsg.class);
    }

    /**
     * 用户登录
     *
     * @param appId
     * @param username username 的值可以为用户的 username/email/phone
     * @param password
     * @return
     */
    public static UserTokenMsg loginPhone(String appId, String username, String password) {
        String ipAddr = WebClientUtils.getIpAddr(WebUtils.getRequest());
        logger.info("OpenApi-》用户{}登录地址：{}", username, ipAddr);
        String result = HttpClientUtil.httpRequest(OpenUrl.LOGIN.getUri(), OpenUrl.LOGIN.getHeaderMap(appId), MapJsonUtils.put(new String[]{"username", username}, new String[]{"password", password}, new String[]{"ip", ipAddr}), OpenUrl.anonymousLogin.getMethodType());
        return JSON.parseObject(result, UserTokenMsg.class);
    }

    /**
     * 修改用户信息
     *
     * @param appId
     * @param token
     * @param appUserUpdateDto
     * @return {
     * “updatedAt”：string
     * }
     */
    public static JSONObject updateAppUser(String appId, String token, AppUserUpdateDto appUserUpdateDto) {
        String result = HttpClientUtil.httpRequest(OpenUrl.UPDATE_USER.getUri(), OpenUrl.UPDATE_USER.getHeaderMap(appId, token), JSON.toJSONString(appUserUpdateDto), OpenUrl.CREATE_USER.getMethodType());
        return JSON.parseObject(result);
    }

    /**
     * 重设密码
     *
     * @param appId
     * @param phone
     * @param newPwd
     * @param code
     * @return
     */
    public static JSONObject resetPassword(String appId, String phone, String newPwd, String code) {
        String result = HttpClientUtil.httpRequest(OpenUrl.resetPassword.getUri(), OpenUrl.resetPassword.getHeaderMap(appId), MapJsonUtils.put(new String[][]{{"phone", phone}, {"new_pwd", newPwd}, {"code", code}}), OpenUrl.resetPassword.getMethodType());
        return JSON.parseObject(result);
    }


    /**
     * 修改密码
     *
     * @param appId
     * @param token
     * @param oldPwd
     * @param newPwd
     * @return
     */
    public static JSONObject modifyPassword(String appId,String token,String oldPwd, String newPwd) {
        String result = HttpClientUtil.httpRequest(OpenUrl.modifyPassword.getUri(), OpenUrl.modifyPassword.getHeaderMap(appId, token), MapJsonUtils.put(new String[][]{{"old_pwd", oldPwd}, {"new_pwd", newPwd}}), OpenUrl.modifyPassword.getMethodType());
        return JSON.parseObject(result);
    }

    /**
     * 获取用户信息
     *
     * @param appId
     * @param token
     * @return
     */
    public static JSONObject getAppUser(String appId, String token) {
        String result = HttpClientUtil.httpRequest(OpenUrl.GET_USER.getUri(), OpenUrl.GET_USER.getHeaderMap(appId, token), "", OpenUrl.GET_USER.getMethodType());
        return JSON.parseObject(result);
    }


    /**
     * 根据 Did 绑定设备
     *
     * @param appId
     * @param token
     * @param bindDidDeviceInfo
     * @return
     */
    public static BindAndUnbindStatus bindDid(String appId, String token, BindDidDeviceInfo bindDidDeviceInfo) {
        String result = HttpClientUtil.httpRequest(OpenUrl.bindDid.getUri(),
                OpenUrl.bindDid.getHeaderMap(appId, token),
                bindDidDeviceInfo.toJsonString(), OpenUrl.bindDid.getMethodType());
        return JSON.parseObject(result, BindAndUnbindStatus.class);
    }

    /**
     * 根据 Did 解除绑定设备
     *
     * @param appId
     * @param token
     * @param unBindDidDeviceInfo
     * @return
     */
    public static BindAndUnbindStatus unbindDid(String appId, String token, UnBindDidDeviceInfo unBindDidDeviceInfo) {
        String result = HttpClientUtil.httpRequest(OpenUrl.unbind.getUri(),
                OpenUrl.unbind.getHeaderMap(appId, token),
                JSONObject.toJSONString(unBindDidDeviceInfo), OpenUrl.unbind.getMethodType());
        return JSON.parseObject(result, BindAndUnbindStatus.class);
    }

    /**
     * 通过did解绑
     *
     * @param appId
     * @param token
     * @param unbindDeviceBody
     * @return
     */
    public static BindAndUnbindStatus unbindByDids(String appId, String token, UnbindDeviceBody unbindDeviceBody) {
        String result = HttpClientUtil.httpRequest(OpenUrl.unbind.getUri(),
                OpenUrl.unbind.getHeaderMap(appId, token),
                JSONObject.toJSONString(unbindDeviceBody), OpenUrl.unbind.getMethodType());
        return JSON.parseObject(result, BindAndUnbindStatus.class);
    }

    /**
     * 获取app token
     *
     * @param appId
     * @param appSecret
     * @return
     */
    public static RequestTokenResult requestToken(String appId, String appSecret) {
        String auth = EncryptionUtils.md5(appId + appSecret).toLowerCase();
        String result = HttpClientUtil.httpRequest(OpenUrl.request_token.getUri(),
                OpenUrl.request_token.getHeaderMap(appId, auth),
                "", OpenUrl.request_token.getMethodType());
        return JSON.parseObject(result, RequestTokenResult.class);
    }

    public static String requestSmsCode(String appId,String token, String phone, String code) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone",phone);
        if(StringUtils.isNotEmpty(code)) {
            jsonObject.put("code", code);
        }
        String result = HttpClientUtil.httpRequest(OpenUrl.sms_code.getUri(),
                OpenUrl.sms_code.getHeaderMap(appId, token),
                jsonObject.toJSONString(), OpenUrl.sms_code.getMethodType());

        return result;
    }

    /**
     * 注册用户 通过用户名，密码
     *
     * @param appId
     * @param username
     * @param password
     * @return
     */
    public static UserTokenMsg registerUsername(String appId, String username, String password) {
        String result = HttpClientUtil.httpRequest(OpenUrl.CREATE_USER.getUri(),
                OpenUrl.CREATE_USER.getHeaderMap(appId),
                MapJsonUtils.put(new String[]{"username", username},
                        new String[]{"password", password}),
                OpenUrl.CREATE_USER.getMethodType());
        return JSON.parseObject(result, UserTokenMsg.class);
    }

    /**
     * 获取聚合数据
     *
     * @param appId
     * @param token
     * @param requestBody
     * @return
     */
    public static AggDataList getAggData(String appId, String token, AggDataRequestBody requestBody) {
        String result = HttpClientUtil.httpRequest(OpenUrl.aggData.getUri(requestBody.getDid()),
                OpenUrl.aggData.getHeaderMap(appId, token),
                MapJsonUtils.put(new String[]{"start_ts", requestBody.getStart_ts()},
                        new String[]{"end_ts", requestBody.getEnd_ts()},
                        new String[]{"attrs", requestBody.getAttrs()},
                        new String[]{"aggregator", requestBody.getAggregator()},
                        new String[]{"unit", requestBody.getUnit()}),
                OpenUrl.aggData.getMethodType());
        return JSON.parseObject(result, AggDataList.class);
    }

    /**
     * 注册第三方用户 通过第三方uid,token
     * @param appId
     * @param src
     * @param uid
     * @param token
     * @return
     */
    public static UserTokenMsg registerBySrc(String appId,String src, String uid, String token) {
        JSONObject json = new JSONObject();
        json.put("src", src);
        json.put("uid", uid);
        json.put("token", token);
        JSONObject jsonF = new JSONObject();
        jsonF.put("authData",json);
        String result = HttpClientUtil.httpRequest(OpenUrl.anonymousLogin.getUri(),
                OpenUrl.anonymousLogin.getHeaderMap(appId),
                jsonF.toJSONString(),
                OpenUrl.anonymousLogin.getMethodType());
        return JSON.parseObject(result, UserTokenMsg.class);
    }
}
